package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.statement.select.Offset;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.SystemConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private final StringRedisTemplate redisTemplate;
    private static final String SIGN_PREFIX = "sign:";

    /**
     * 发送验证码
     *
     * @param phone
     * @param session
     * @return
     */
    public Result sendCode(String phone, HttpSession session) {
        // 1.校验手机号格式
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号格式错误");
        }
        // 2.生成验证码
        String code = RandomUtil.randomNumbers(6);
        //3. 保存验证码到redis
        redisTemplate.opsForValue().set(LOGIN_CODE_KEY + phone, code, Duration.ofMinutes(5L));
        //4.日志
        log.debug("验证码发送成功：{}", code);
        //5.返回验证码
        return Result.ok(code);
    }

    /**
     * 用户登录
     *
     * @param loginForm
     * @param session
     * @return
     */
    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        // 1.校验手机号格式
        if (RegexUtils.isPhoneInvalid(loginForm.getPhone())) {
            // 手机号格式错误
            return Result.fail("手机号格式错误");
        }
        // 2.校验验证码
        String code = loginForm.getCode();
        String key = LOGIN_CODE_KEY + loginForm.getPhone();
        String redisCode = redisTemplate.opsForValue().get(key);
        if (redisCode == null || !redisCode.equals(code)) {
            return Result.fail("验证码错误");
        }
        // 3.验证码通过,删除redis
        redisTemplate.delete(key);

        //4. 根据手机号查询用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", loginForm.getPhone());
        //4. 判断用户是否存在
        User user = getOne(queryWrapper);
        //4.1 存在,token写入redis
        String token = UUID.randomUUID().toString(true);
        if (user != null) {
            user.setPassword(null);
            // 写入redis
            String tokenKey = LOGIN_USER_KEY + token;
            Map<String, Object> map = BeanUtil.beanToMap(user, new HashMap<>(),
                    CopyOptions.create()
                            .setIgnoreNullValue(true)
                            .setFieldValueEditor((filed, value) -> value.toString())
                            .setIgnoreProperties("password", "createTime", "updateTime")
            );
            //  先存储
            redisTemplate.opsForHash().putAll(tokenKey, map);
            // 设置有效期
            redisTemplate.expire(tokenKey, Duration.ofMinutes(LOGIN_USER_TTL));
        } else {
            //4.2 不存在,创建新用户
            createNewUser(loginForm);
        }
        return Result.ok(token);
    }

    /**
     * 用户登出
     */
    @Override
    public void logout(String token) {
        //1. 获取用户
        UserDTO user = UserHolder.getUser();
        //2. 删除用户
        //2.1 删除hreadLoacl
        UserHolder.removeUser();
        //2.2 删除redis
        String key = LOGIN_USER_KEY + token;
        redisTemplate.delete(key);
    }

    /**
     * 用户签到
     */
    @Override
    public void sign() {
        // 获取用户信息
        String userId = UserHolder.getUser().getId().toString();
        // 获取当前日期
        LocalDateTime now = LocalDateTime.now();
        String month = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        int day = now.getDayOfMonth();
        // 写入redis
        String key = SIGN_PREFIX + userId  + month;
        redisTemplate.opsForValue().setBit(key, day - 1, true);
    }

    public int signCountOfMonth() {
        // 获取用户信息
        String userId = UserHolder.getUser().getId().toString();
        // 获取当前日期
        LocalDateTime now = LocalDateTime.now();
        String month = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        int day = now.getDayOfMonth();
        //去redis中查询
        String key = SIGN_PREFIX + userId + month;
        List<Long> longs = redisTemplate.opsForValue().bitField(key,
                BitFieldSubCommands.create()
                        .get(BitFieldSubCommands.BitFieldType.unsigned(day)).valueAt(0));
        if (CollUtil.isEmpty(longs)) {
            return 0;
        }
        Long num = longs.get(0);

        int count = 0;
        // 未签到
        while ((num & 1) != 0) {
            count++;
            num >>>= 1;
        }
        return count;
    }


    public void createNewUser(LoginFormDTO loginForm) {
        User newUser = new User();
        newUser.setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));
        newUser.setPhone(loginForm.getPhone());
        save(newUser);
    }
}
